/**
 * File: MaqContigExec.java
 * Created by: mhaimel
 * Created on: 1 Apr 2009
 * CVS:  $Id: MaqContigExec.java,v 1.1 2009/04/22 07:38:10 mhaimel Exp $
 */
package uk.ac.ebi.velvet.exec.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.velvet.config.VelvetConfig;
import uk.ac.ebi.velvet.exec.ProcessorService;
import uk.ac.ebi.velvet.util.config.ConfigFactory;

/**
 * @author mhaimel
 *
 */
public class MaqContigExec extends AbstractExec {
	private static final String FASTA2BFA_OPT = "fasta2bfa";
	private Log log = LogFactory.getLog(this.getClass());
	private VelvetConfig config;
	private File baseDir;
	private ProcessorService pc = null;
	
	public MaqContigExec(File baseDir) {
		super();
		this.baseDir = baseDir;
	}
	
	public void runMaqFasta2Bfa(FileInfo contig, File fasta2bfa){
		getLog().info("Transform Contig 2 maq bfa file ...");
		File fa = getFastaFile(contig);
		List<String> cmds = new ArrayList<String>();
		cmds.add(getMaqExecCmd());
		cmds.add(FASTA2BFA_OPT);
		cmds.add(fa.getAbsolutePath());
		cmds.add(fasta2bfa.getAbsolutePath());
		File logFile = getNextFile(getBaseDir(), fasta2bfa.getName()+"_", ".log");
		File errFile = getNextFile(getBaseDir(), fasta2bfa.getName()+"_", ".err");
		exec(getBaseDir(), cmds.toArray(new String[0]), logFile, errFile,false,true);
		getLog().info("Finished transforming Contig 2 maq file!");
	}

	private String getMaqExecCmd() {
		String cmd = getConfig().getMaqExec();
		if(StringUtils.isEmpty(cmd)){
			throw new IllegalArgumentException(
					"No Maq executeable command provided!!");
		}
		return cmd;
	}	

	private File getFastaFile(FileInfo contig) {
		if(contig.getFileType().equals(FileType.fasta)){
			return contig.getFile();
		} else {
			throw new IllegalArgumentException(
					"Only Contig files in fasta supported for now!");
		}
	}

	private VelvetConfig getConfig() {
		if(null == config){
			config = ConfigFactory.create(VelvetConfig.class);
		}
		return config;
	}

	private File getBaseDir() {
		return baseDir;
	}
	private Log getLog() {
		return log;
	}
	
	public void setProcessorService(ProcessorService pc){
		this.pc = pc;
	}

	@Override
	protected ProcessorService getProcessorService() {
		return pc;
	}
}
